package org.zwy.gradetrack.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.zwy.gradetrack.common.Result;
import org.zwy.gradetrack.entity.Course;
import org.zwy.gradetrack.entity.CourseSupportMatrix;
import org.zwy.gradetrack.entity.Indicator;
import org.zwy.gradetrack.service.CourseSupportMatrixService;
import org.zwy.gradetrack.service.CourseService;
import org.zwy.gradetrack.service.IndicatorService;

import java.util.List;

/**
 * 课程支撑矩阵管理控制器
 */
@RestController
@RequestMapping("/api/course-support-matrices")
public class CourseSupportMatrixController {

    @Autowired
    private CourseSupportMatrixService courseSupportMatrixService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private IndicatorService indicatorService;

    /**
     * 获取支撑矩阵列表
     */
    @GetMapping
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER','GRADUATE')")
    public Result<List<CourseSupportMatrix>> getMatrixList(
            @RequestParam(required = false) Long courseId,
            @RequestParam(required = false) Long indicatorId) {
        List<CourseSupportMatrix> matrices;
        if (courseId != null) {
            // 检查课程是否存在
            if (!courseService.lambdaQuery()
                    .eq(Course::getId, courseId)
                    .exists()) {
                return Result.error(404, "课程不存在");
            }
            
            matrices = courseSupportMatrixService.lambdaQuery()
                    .eq(CourseSupportMatrix::getCourseId, courseId)
                    .list();
        } else if (indicatorId != null) {
            // 检查指标点是否存在
            if (!indicatorService.lambdaQuery()
                    .eq(Indicator::getId, indicatorId)
                    .exists()) {
                return Result.error(404, "指标点不存在");
            }
            
            matrices = courseSupportMatrixService.lambdaQuery()
                    .eq(CourseSupportMatrix::getIndicatorId, indicatorId)
                    .list();
        } else {
            matrices = courseSupportMatrixService.list();
        }
        return Result.success(matrices);
    }

    /**
     * 创建支撑矩阵
     */
    @PostMapping
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<CourseSupportMatrix> createMatrix(@RequestBody CourseSupportMatrix matrix) {
        // 检查课程是否存在
        if (!courseService.lambdaQuery()
                .eq(Course::getId, matrix.getCourseId())
                .exists()) {
            return Result.error(404, "课程不存在");
        }

        // 检查指标点是否存在
        if (!indicatorService.lambdaQuery()
                .eq(Indicator::getId, matrix.getIndicatorId())
                .exists()) {
            return Result.error(404, "指标点不存在");
        }

        // 检查支撑矩阵是否已存在
        if (courseSupportMatrixService.lambdaQuery()
                .eq(CourseSupportMatrix::getCourseId, matrix.getCourseId())
                .eq(CourseSupportMatrix::getIndicatorId, matrix.getIndicatorId())
                .exists()) {
            return Result.error(400, "该课程对指标点的支撑关系已存在");
        }

        // 保存支撑矩阵信息
        courseSupportMatrixService.save(matrix);
        return Result.success(matrix);
    }

    /**
     * 更新支撑矩阵
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<CourseSupportMatrix> updateMatrix(@PathVariable Long id, @RequestBody CourseSupportMatrix matrix) {
        // 检查支撑矩阵是否存在
        if (!courseSupportMatrixService.lambdaQuery()
                .eq(CourseSupportMatrix::getId, id)
                .exists()) {
            return Result.error(404, "支撑矩阵不存在");
        }

        // 检查课程是否存在
        if (!courseService.lambdaQuery()
                .eq(Course::getId, matrix.getCourseId())
                .exists()) {
            return Result.error(404, "课程不存在");
        }

        // 检查指标点是否存在
        if (!indicatorService.lambdaQuery()
                .eq(Indicator::getId, matrix.getIndicatorId())
                .exists()) {
            return Result.error(404, "指标点不存在");
        }

        // 检查支撑矩阵是否重复
        if (courseSupportMatrixService.lambdaQuery()
                .eq(CourseSupportMatrix::getCourseId, matrix.getCourseId())
                .eq(CourseSupportMatrix::getIndicatorId, matrix.getIndicatorId())
                .ne(CourseSupportMatrix::getId, id)
                .exists()) {
            return Result.error(400, "该课程对指标点的支撑关系已存在");
        }

        // 更新支撑矩阵信息
        matrix.setId(id);
        courseSupportMatrixService.updateById(matrix);
        return Result.success(matrix);
    }

    /**
     * 删除支撑矩阵
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('SYSTEM_ADMIN')")
    public Result<Void> deleteMatrix(@PathVariable Long id) {
        // 检查支撑矩阵是否存在
        if (!courseSupportMatrixService.lambdaQuery()
                .eq(CourseSupportMatrix::getId, id)
                .exists()) {
            return Result.error(404, "支撑矩阵不存在");
        }

        // 删除支撑矩阵
        courseSupportMatrixService.removeById(id);
        return Result.success();
    }

    /**
     * 获取支撑矩阵详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('SYSTEM_ADMIN', 'TEACHER','GRADUATE')")
    public Result<CourseSupportMatrix> getMatrixDetail(@PathVariable Long id) {
        CourseSupportMatrix matrix = courseSupportMatrixService.getById(id);
        if (matrix == null) {
            return Result.error(404, "支撑矩阵不存在");
        }
        return Result.success(matrix);
    }
} 